package org.example.projectdemo.controller;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import org.example.projectdemo.model.entity.Attendance;
import org.example.projectdemo.model.entity.Schedule;
import org.example.projectdemo.model.entity.Student;
import org.example.projectdemo.service.AttendanceService;
import org.example.projectdemo.service.ScheduleService;
import org.example.projectdemo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * ClassName: AttendanceController
 * Package: org.example.projectdemo.controller
 * Description:
 *
 * @Author ZY
 * @Create 00:00
 * @Version 1.0
 */
/**
 * 考勤管理控制器
 * 处理学生考勤相关的HTTP请求
 */
@RestController
@RequestMapping("/api/attendances")
@Validated
public class AttendanceController {
    @Autowired
    private AttendanceService attendanceService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private ScheduleService scheduleService;

    /**
     * 创建考勤记录
     *
     * @param attendance 考勤信息
     * @return 创建后的考勤记录
     */
    @PostMapping
    public ResponseEntity<Attendance> createAttendance(@Valid @RequestBody Attendance attendance) {
        Attendance savedAttendance = attendanceService.createAttendance(attendance);
        return ResponseEntity.ok(savedAttendance);
    }

    /**
     * 更新考勤记录
     *
     * @param id 考勤记录ID
     * @param attendance 考勤信息
     * @return 更新后的考勤记录
     */
    @PutMapping("/{id}")
    public ResponseEntity<Attendance> updateAttendance(@PathVariable Long id, 
                                                       @Valid @RequestBody Attendance attendance) {
        attendance.setId(id);
        try {
            Attendance updatedAttendance = attendanceService.updateAttendance(attendance);
            return ResponseEntity.ok(updatedAttendance);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 根据ID获取考勤记录
     *
     * @param id 考勤记录ID
     * @return 考勤记录信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<Attendance> getAttendanceById(@PathVariable Long id) {
        Optional<Attendance> attendance = attendanceService.getAttendanceById(id);
        return attendance.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 获取所有考勤记录列表
     *
     * @return 所有考勤记录列表
     */
    @GetMapping
    public ResponseEntity<List<Attendance>> getAllAttendances() {
        List<Attendance> attendances = attendanceService.getAllAttendances();
        return ResponseEntity.ok(attendances);
    }

    /**
     * 根据学生ID获取考勤记录
     *
     * @param studentId 学生ID
     * @return 该学生的考勤记录列表
     */
    @GetMapping("/by-student/{studentId}")
    public ResponseEntity<List<Attendance>> getAttendancesByStudent(@PathVariable Long studentId) {
        List<Attendance> attendances = attendanceService.getAttendancesByStudentId(studentId);
        return ResponseEntity.ok(attendances);
    }

    /**
     * 根据排课ID获取考勤记录
     *
     * @param scheduleId 排课ID
     * @return 该次课程的考勤记录列表
     */
    @GetMapping("/by-schedule/{scheduleId}")
    public ResponseEntity<List<Attendance>> getAttendancesBySchedule(@PathVariable Long scheduleId) {
        List<Attendance> attendances = attendanceService.getAttendancesByScheduleId(scheduleId);
        return ResponseEntity.ok(attendances);
    }

    /**
     * 学生签到接口
     * 根据学生ID和排课ID创建或更新签到记录
     *
     * @param studentId 学生ID
     * @param scheduleId 排课ID
     * @return 签到后的考勤记录
     */
    @PostMapping("/check-in")
    public ResponseEntity<?> studentCheckIn(
            @NotNull @Min(1) @RequestParam Long studentId,//@NotNull: 防止 null ; @Min(1): 防止负数或 0
            @NotNull @Min(1) @RequestParam Long scheduleId) {

        try {
            // 1. 验证学生和排课是否存在
            Student student = studentService.getStudentById(studentId)
                    .orElseThrow(() -> new RuntimeException("学生ID不存在: " + studentId));
            Schedule schedule = scheduleService.getScheduleById(scheduleId)
                    .orElseThrow(() -> new RuntimeException("排课ID不存在: " + scheduleId));

            // 2. 检查是否已经签到
            Optional<Attendance> existingAttendance = attendanceService.getAttendanceByStudentAndSchedule(studentId, scheduleId);
            Attendance attendance;

            if (existingAttendance.isPresent()) {
                // 更新现有记录（比如重复签到更新时间）
                attendance = existingAttendance.get();
                attendance.setCheckInTime(LocalTime.now());
                attendance.setRemark("重新签到于: " + LocalDateTime.now());
                attendance = attendanceService.updateAttendance(attendance);
            } else {
                // 创建新记录
                attendance = new Attendance();
                attendance.setStudent(student); // 设置学生对象关联
                attendance.setSchedule(schedule); // 设置排课对象关联
                attendance.setCheckInTime(LocalTime.now());
                attendance.setRemark("首次签到");
                attendance = attendanceService.createAttendance(attendance);
            }

            return ResponseEntity.ok(attendance);

        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 批量考勤接口
     * 为多个学生创建考勤记录
     *
     * @param requestData 包含排课ID、考勤日期和学生考勤状态的批量数据
     * @return 创建成功的考勤记录列表
     */
    @PostMapping("/batch")
    public ResponseEntity<?> batchAttendance(@RequestBody Map<String, Object> requestData) {
        try {
            System.out.println("批量考勤请求数据: " + requestData);
            
            // 安全地提取请求参数
            Object scheduleIdObj = requestData.get("scheduleId");
            Object attendanceDateObj = requestData.get("attendanceDate");
            Object studentAttendancesObj = requestData.get("studentAttendances");
            
            if (scheduleIdObj == null || attendanceDateObj == null || studentAttendancesObj == null) {
                return ResponseEntity.badRequest().body("缺少必要参数: scheduleId, attendanceDate, studentAttendances");
            }
            
            Long scheduleId = Long.valueOf(scheduleIdObj.toString());
            String attendanceDateStr = attendanceDateObj.toString();
            LocalDate attendanceDate = LocalDate.parse(attendanceDateStr);
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> studentAttendances = (List<Map<String, Object>>) studentAttendancesObj;
            
            if (studentAttendances == null || studentAttendances.isEmpty()) {
                return ResponseEntity.badRequest().body("学生考勤数据不能为空");
            }
            
            System.out.println("排课ID: " + scheduleId + ", 考勤日期: " + attendanceDate + ", 学生数量: " + studentAttendances.size());
            
            // 验证排课是否存在
            Schedule schedule = scheduleService.getScheduleById(scheduleId)
                    .orElseThrow(() -> new RuntimeException("排课ID不存在: " + scheduleId));
            
            // 批量创建考勤记录
            List<Attendance> createdAttendances = attendanceService.batchCreateAttendance(
                scheduleId, attendanceDate, studentAttendances);
            
            System.out.println("批量考勤创建成功，记录数: " + createdAttendances.size());
            return ResponseEntity.ok(createdAttendances);
            
        } catch (Exception e) {
            System.err.println("批量考勤失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body("批量考勤失败: " + e.getMessage());
        }
    }

    /**
     * 删除考勤记录
     *
     * @param id 考勤记录ID
     * @return 删除成功返回200
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteAttendance(@PathVariable Long id) {
        if (!attendanceService.existsAttendanceById(id)) {
            return ResponseEntity.notFound().build();
        }
        attendanceService.deleteAttendance(id);
        return ResponseEntity.ok().build();
    }
}